<script setup lang="ts">
import { ref, reactive } from 'vue'
import type { rechargePlanItem } from '@/types/member'
import { getRechargeCenterApi, postRechargeApi } from '@/api/recharge'
import { onShowRefreshData } from '@/utils/common'
import { getMemberProfileApi } from '@/api/member'

// 充值面额
const planList = ref<rechargePlanItem[]>([])

const state = reactive({
  balance: '0.00',
  rechargeMoney: '',
  customMoney: '',
})

// 选择充值面额
const selectedPlanId = ref(0)
const onSelectPlan = (id: number) => {
  selectedPlanId.value = id
  state.customMoney = ''
  state.rechargeMoney = planList.value.find((item) => item.id === id)!.money
}

// 获取充值面额
const getRechargePlan = async () => {
  const res = await getRechargeCenterApi()
  planList.value = res.result.planList
  if (planList.value.length > 0) {
    onSelectPlan(planList.value[0].id)
  }
}

// 获取自定义充值金额
const onGetRechargeMoeny = () => {
  state.customMoney = state.customMoney.replaceAll(' ', '')
  if (state.customMoney) {
    state.customMoney = parseFloat(state.customMoney).toFixed(2)
  }
  state.rechargeMoney = state.customMoney
}
const onFoucsCustomMoney = () => {
  selectedPlanId.value = 0
  state.rechargeMoney = ''
}

//校验输入金额
const checkRechargeMoney = (money: string) => {
  const moneyFloat = parseFloat(money)
  if (isNaN(moneyFloat)) {
    uni.showToast({
      title: 'The recharge amount is incorrect',
      icon: 'none',
    })
    return false
  }
  if (moneyFloat < 0.01) {
    uni.showToast({
      title: 'The recharge amount needs to be greater than 0.01 yuan',
      icon: 'none',
    })
    return false
  }
  //除去多余的0
  state.rechargeMoney = moneyFloat.toFixed(2)

  return true
}

const payWay = ref('')

// 支付方式
// #ifdef WEB
payWay.value = 'alipay'
// #endif

// #ifdef MP-WEIXIN
payWay.value = 'wxpay'
// #endif

// 切换支付方式
const onChangePayWay = (event: UniHelper.RadioGroupOnChangeEvent) => {
  console.log(event.detail.value)
}

// 提交充值
const onSubmit = async () => {
  if (checkRechargeMoney(state.rechargeMoney)) {
    const res = await postRechargeApi({
      plan_id: selectedPlanId.value,
      custom_amount: state.customMoney,
      pay_way: payWay.value,
    })
    if (!res.result) {
      failHandle()
    }
    //发起支付
    switch (payWay.value) {
      case 'wxpay':
        doWxPay(res.result)
        break
      case 'alipay':
        doAlipay(res.result)
        break
      default:
        failHandle()
    }
  }
}

//发起微信支付
const doWxPay = (paymentParams: WechatMiniprogram.RequestPaymentOption) => {
  wx.requestPayment({
    ...paymentParams,
    success: () => {
      successHandle()
    },
    fail: (fail) => {
      uni.showToast({
        title: 'Payment failed',
        icon: 'error',
      })
      console.warn('支付失败：')
      console.warn(fail)
    },
  })
}

const doAlipay = (result: any) => {
  wx.showLoading({
    title: 'Payment in progress…',
    mask: true,
  })

  location.href = result.url
}

const successHandle = () => {
  uni.showToast({
    title: 'Recharge successful',
    icon: 'success',
  })
  setTimeout(() => {
    uni.navigateBack()
  }, 1500)
}

const failHandle = () => {
  uni.showToast({
    title: 'Recharge failed',
    icon: 'none',
  })
  return
}

onShowRefreshData(() => {
  getMemberProfileApi().then((res) => {
    state.balance = res.result.money!
  })
  getRechargePlan()
})
</script>

<template>
  <view class="container">
    <view class="balance-panel">
      <view class="text">Account Balance</view>
      <view class="money">
        <view class="money-text">{{ state.balance }}</view>
      </view>
    </view>
    <!-- 充值面板 -->
    <view class="recharge-panel">
      <view class="recharge-label">
        <text>Recharge Amount</text>
      </view>
      <view class="recharge-plan clearfix">
        <block v-for="(item, index) in planList" :key="index">
          <view
            class="recharge-plan-item"
            :class="{ active: selectedPlanId == item.id }"
            @tap="onSelectPlan(item.id)"
          >
            <view v-if="parseFloat(item.gift_money) > 0" class="item-tag">
              <view class="plan-money">
                <text>{{ item.money }} USD</text>
              </view>
              <view class="plan-gift">
                <text>Gift {{ item.gift_money }} USD</text>
              </view>
            </view>
            <view v-else class="item-tag">
              <view class="plan-only-money">
                <text>{{ item.money }} USD</text>
              </view>
            </view>
          </view>
        </block>
        <!-- 手动充值输入框 -->
        <label>
          <view class="recharge-plan-item" :class="{ active: state.customMoney != '' }">
            <view class="recharge-plan-input" v-if="true">
              <input
                class="input"
                type="digit"
                placeholder="Other Amount"
                v-model="state.customMoney"
                @blur="onGetRechargeMoeny"
                @focus="onFoucsCustomMoney"
              />
            </view>
          </view>
        </label>
      </view>
      <!-- 注意事项 -->
      <view class="recharge-notice">
        <view class="notice-head">
          <text>Warm Reminder:</text>
        </view>
        <view class="notice-content">
          <text class="notice-item">1. Recharge amount will be credited immediately and cannot be refunded after successful recharge;</text>
          <text class="notice-item">2. Gift amount will be credited immediately and valid until used up from the recharge date;</text>
          <text class="notice-item">3. For other recharge issues, please contact customer service.</text>
        </view>
      </view>
    </view>
    <!-- 支付方式 -->
    <view class="recharge-pay">
      <radio-group @change="onChangePayWay">
        <!-- #ifdef MP-WEIXIN -->
        <label class="recharge-pay-item">
          <view>
            <uni-icons
              custom-prefix="iconfont"
              type="icon-wechat-pay"
              size="18"
              color="#09bb07"
              class="icon-class"
            ></uni-icons>
            <text style="margin-left: 10rpx">WeChat Pay</text>
          </view>
          <view> <radio value="wxpay" :checked="payWay === 'wxpay'" /> </view>
        </label>
        <!-- #endif -->
        <!-- #ifdef WEB -->
        <label class="recharge-pay-item">
          <view>
            <uni-icons
              custom-prefix="iconfont"
              type="icon-alipay"
              size="18"
              color="#007aff"
              class="icon-class"
            ></uni-icons>
            <text style="margin-left: 10rpx">Alipay</text>
          </view>
          <view> <radio value="alipay" :checked="payWay === 'alipay'" /> </view>
        </label>
        <!-- #endif -->
      </radio-group>
    </view>
  </view>
  <shop-submit-button @tap="onSubmit" title="Recharge immediately" />
</template>

<style lang="scss">
page {
  background-color: #f5f5f5;
}

.container {
  padding: 30rpx;

  .balance-panel {
    background-color: #ff5f3c;
    border-radius: 30rpx;
    display: flex;
    flex-direction: column;
    align-items: center;

    .text {
      color: #fff;
      padding: 20rpx;
    }

    .money {
      position: relative;
      margin: 20rpx;
      font-size: 50rpx;
      color: #fff;

      &-text {
        margin-left: 30rpx;
      }
    }

    .money::before {
      content: '$';
      position: absolute;
      bottom: 0;
      left: 0;
      font-size: 35rpx;
      color: #fff;
      padding-right: 5px;
    }
  }

  .recharge-panel {
    margin-top: 30rpx;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    padding: 30rpx;
    border-radius: 30rpx;

    .recharge-plan {
      .recharge-plan-item {
        width: 192rpx;
        padding: 15rpx 0;
        float: left;
        text-align: center;
        color: #888;
        border: 1rpx solid rgb(228, 228, 228);
        border-radius: 10rpx;
        margin: 0 15rpx 20rpx 0;

        &:nth-child(3n + 0) {
          margin-right: 0;
        }

        &.active {
          color: #ff0040;
          border: 1rpx solid #ff0040;

          .plan-money {
            color: #ff0040;
          }
        }

        .item-tag {
          height: 80rpx;
          display: flex;
          flex-direction: column;
          justify-content: center;
        }

        .plan-money {
          font-size: 32rpx;
          color: rgb(82, 82, 82);
        }

        .plan-gift {
          font-size: 20rpx;
          padding-top: 10rpx;
        }

        .plan-only-money {
          color: #525252;
        }
      }

      .recharge-plan-input {
        display: flex;
        justify-content: center;
        align-items: center;
        width: 192rpx;
        height: 76rpx;

        .input {
          display: block;
          border-radius: 10rpx;
          font-size: 28rpx;
          text-align: center;
          padding: 0rpx 10rpx 0rpx 10rpx;
        }
      }
    }

    .recharge-notice {
      padding-top: 30rpx;
      padding-bottom: 10rpx;

      .notice-head {
        font-size: 28rpx;
        color: #525252;
      }

      .notice-content {
        display: flex;
        flex-direction: column;
        font-size: 24rpx;
        color: #8c8c8c;
      }

      .notice-item {
        margin-top: 10rpx;
      }
    }
  }

  .recharge-label {
    margin-bottom: 30rpx;
  }

  .recharge-pay {
    margin-top: 30rpx;
    background-color: #fff;
    display: flex;
    flex-direction: column;
    padding: 30rpx;
    border-radius: 20rpx;

    .recharge-pay-item {
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
